#!/usr/bin/env python3
"""
检查并创建管理员用户
"""

import asyncio

from sqlalchemy import select
from sqlalchemy.engine import Result

from app.database.session import AsyncSessionLocal
from app.models.user import User

# 管理员用户配置
ADMIN_USERS: list[dict[str, str]] = [
    {
        "username": "admin",
        "email": "admin@example.com",
        "password": "admin123",
        "role": "admin",
        "full_name": "管理员"
    },
    {
        "username": "suadmin",
        "email": "suadmin@example.com",
        "password": "suadmin123",
        "role": "super_admin",
        "full_name": "超级管理员"
    }
]


async def check_and_create_admin_users() -> None:
    """检查并创建管理员用户"""
    async with AsyncSessionLocal() as session:
        # 查询现有用户
        result: Result[tuple[User]] = await session.execute(select(User))
        existing_users: list[User] = list(result.scalars().all())

        # 检查需要创建的用户
        existing_usernames: set[str] = {user.username for user in existing_users}
        missing_users: list[dict[str, str]] = [
            user for user in ADMIN_USERS
            if user["username"] not in existing_usernames
        ]

        if not missing_users:
            print("所有管理员用户已存在")
            return

        # 创建缺失的用户
        for user_data in missing_users:
            from passlib.context import CryptContext
            pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
            
            hashed_password = pwd_context.hash(user_data["password"])
            
            new_user = User(
                username=user_data["username"],
                email=user_data["email"],
                hashed_password=hashed_password,
                role=user_data["role"],
                full_name=user_data["full_name"],
                is_active=True
            )
            session.add(new_user)
            print(f"创建用户: {user_data['username']} ({user_data['role']})")

        await session.commit()
        print(f"成功创建 {len(missing_users)} 个管理员用户")


if __name__ == "__main__":
    asyncio.run(check_and_create_admin_users())